<template>
  <div class="tree">
    <div class="custom-tree-container">
      <el-tree style="max-width: 300px" node-key="id" :expand-on-click-node="false" lazy :load="loadNode"
        :render-content="renderContent" default-expand-all :key="treeKey" @node-click="handleNodeClick" />
    </div>
    <!-- 弹框 -->
    <el-dialog :title="title" v-model="centerDialogVisible" width="40%">
      <p>当前出于的广告位置：{{ advertInfo.label }}</p>
      <el-input type="text" v-model="input" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submithandle">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, reactive, onMounted,nextTick } from 'vue';
import { Delete, Plus, Edit } from '@element-plus/icons-vue'
//全局导入
const cxt = getCurrentInstance()
const API = cxt.appContext.config.globalProperties.$API
const bus = cxt.appContext.config.globalProperties.$bus
// 定义 Tree 接口
class Tree {
  constructor(id, label, children,pid) {
    this.id = id;
    this.label = label;
    this.children = children || [];
    this.pid = pid;
  }
}
const centerDialogVisible = ref(false)
const title = ref('添加广告')
const input = ref('')
const advertInfo = reactive({})
const treeKey = ref(0);
//tree数据
const selectContentCategoryByParentId = async (id) => {
  const result = await API.selectContentCategoryByParentId({ id })
  if (result.status === 200) {
    // 假设接口返回的数据格式为数组，每个元素包含 id, name, pid 等属性
    const data = result.result.map(item => new Tree(item.id, item.name, [], item.pid));
    return data;
  }
  return [];
}
const loadNode = async(node, resolve) => {
  // console.log(node, resolve);
  let data = [];
  if (node.level === 0) {
    // 加载一级数据
    data = await selectContentCategoryByParentId(null);
  } else if (node.level >= 1) {
    // 加载下一级数据
    data = await selectContentCategoryByParentId(node.data.pid);
  }
  resolve(data);
}
//增加
const append = (data) => {
  // console.log(data);
  //显示弹框
  centerDialogVisible.value= true;
  title.value = "添加广告";
  Object.assign(advertInfo,data)
}
//删除
const remove = async(node, data) => {
  const result = await API.deleteContentCategoryById2({ pid: data.pid })
  // console.log(result);
  if (result.status == 200) {
    treeKey.value++;
  }
}
//修改
const update = (node, data) => {
  centerDialogVisible.value = true;
  title.value = "修改广告";
  Object.assign(advertInfo, data)
  input.value=data.label
}
//点击tree节点---发送数据
const handleNodeClick=(data)=>{
  // console.log(data)
  // this.$emit('getTreeData', data)
  bus.emit('getTreeData', data)
}
const renderContent = (h, { node, data, store }) => {
  // console.log('render--',node,data);
  return h(
    'span',
    {
      class: 'custom-tree-node'
    },
    h('span', { class: 'name' }, node.label),
    h(
      'span',
      null,
      h(
        'button',
        {
          style: 'background-color: #409EFF; color: white; border: none; padding: 5px 10px; border-radius: 3px;  cursor: pointer; ', // 默认颜色
          onClick: () => append(data)
        },
        [h(Plus, { style: 'width: 1em; height: 1em; margin-right: 8px' }), '新增 '] // 添加 Plus 图标
      ),
      h(
        'button',
        {
          style: 'background-color: #409EFF; color: white; border: none; padding: 5px 10px; border-radius: 3px;  cursor: pointer; margin :0 10px', // 默认颜色
          onClick: () => update(node, data)
        },
        [h(Edit, { style: 'width: 1em; height: 1em; margin-right: 8px' }), '修改 ']
      ),
      h(
        'button',
        {
          style: 'background-color: #F56C6C; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer;', // danger 颜色
          onClick: () => remove(node, data)
        },
        [h(Delete, { style: 'width: 1em; height: 1em; margin-right: 8px' }), '删除']
      )
    )
  );
};
//提交
const submithandle = () => {
  if (title.value == "添加广告") {
    //增加
    insertContentCategory({ pid: advertInfo.pid, name: input.value })
  } else if (title.value == "修改广告") {
    //修改
    updateContentCategory({ pid: advertInfo.pid, name: input.value })
  }
}
//新增子类目录名称 cid name
const insertContentCategory = async (params) => {
  const result = await API.insertContentCategory(params)
  // console.log(result);
  if (result.status == 200) {
    centerDialogVisible.value = false;
    treeKey.value++;
  }
}
//修改类目 id name
const updateContentCategory = async (params) => {
  const result = await API.updateContentCategory(params)
  // console.log(result);
  if (result.status == 200) {
    centerDialogVisible.value = false
  }
}
</script>

<style lang="less" scoped>
.tree {
  width: 600px;
  background: #fff;
  margin: 10px;

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  :deep(.mini) {
    padding: 4px 10px;
    font-size: 14px;
  }

  :deep(.el-tree-node__content) {
    margin-bottom: 10px;
  }
}

:deep(.name) {
  width: 280px;
  display: inline-block;
}

:deep(.el-tree-node.is-expanded.is-focusable) {
  width: 600px;
}

</style>